package 尊享面试.哈希;

import java.util.HashMap;
import java.util.Map;

public class a1198找出所有行中最小公共元素 {
    static class Solution {
        public int smallestCommonElement0(int[][] mat) {
            HashMap<Integer, Integer> map = new HashMap<>();
            for (int[] ints : mat) {
                for (int an : ints) {
                    map.put(an, map.getOrDefault(an, 0) + 1);
                }
            }
            int res = Integer.MAX_VALUE;
            for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
                if (entry.getValue().equals(mat.length)) {
                    res = Math.min(entry.getKey(), res);
                }
            }
            return res == Integer.MAX_VALUE ? -1 : res;
        }

        public int smallestCommonElement1(int[][] mat) {
            int[] cnt = new int[10001];
            for (int[] ints : mat) {
                for (int an : ints) {
                    cnt[an]++;
                }
            }
            for (int i = 1; i < 10001; i++) {
                if (cnt[i] == mat.length) {
                    return i;
                }
            }
            return -1;
        }

        public int smallestCommonElement(int[][] mat) {
            int[] cnt = new int[10001];
            int m = mat.length;
            int n = mat[0].length;
            for (int j = 0; j < n; j++) {
                for (int i = 0; i < m; i++) {
                    if (++cnt[mat[i][j]] == m) {
                        return mat[i][j];
                    }
                }
            }
            return -1;
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[][] mat = {{5, 6}, {5, 6}, {5, 6}, {4, 6}};
        System.out.println(solution.smallestCommonElement(mat));
    }
}
